﻿using AnQinFrameWorkAPI.Common.Enum;
using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.Blog.DTO.BlogText;
using AnQinFrameWorkAPI.Entity.Blog.Entity;
using AnQinFrameWorkAPI.Entity.Blog.View.BlogText;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.JWT;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace AnQinFrameWorkAPI.Service.Blog;

/// <summary>
///     博客文章服务
/// </summary>
public class BlogTextService
{
    //数据库
    private readonly DatabaseContext _context;
    
    //自动映射
    private readonly IMapper _mapper;
    
    //请求人信息
    private readonly IUserContext _userContext;

    /// <summary>
    ///     构造函数（依赖注入）
    /// </summary>
    public BlogTextService(DatabaseContext context, IMapper mapper,IUserContext userContext)
    {
        _context = context;
        _mapper = mapper;
        _userContext = userContext;
    }

    #region 获取博客文章列表（分页）

    /// <summary>
    ///     获取博客文章列表（分页）
    /// </summary>
    public async Task<RequestResponseModel> GetBlogTextList(BlogTextSearchDTO searchDTO)
    {
        var query = _context.BlogText
            .ProjectTo<BlogTextView>(_mapper.ConfigurationProvider)
            .AsNoTracking().WhereIF(a => a.Code.Contains(searchDTO.Code), !string.IsNullOrEmpty(searchDTO.Code))
            .WhereIF(a => a.Name.Contains(searchDTO.Name), !string.IsNullOrEmpty(searchDTO.Name))
            .WhereIF(a => a.Content.Contains(searchDTO.Content), !string.IsNullOrEmpty(searchDTO.Content))
            .WhereIF(a => a.Status == searchDTO.Status, searchDTO.Status != null)
            .WhereIF(a => a.CreateTime > searchDTO.StartTime, searchDTO.StartTime != null)
            .WhereIF(a => a.CreateTime < searchDTO.EndTime, searchDTO.EndTime != null);

        var list = await query
            .OrderByDescending(a => a.CreateTime)
            .Page(searchDTO.PageIndex, searchDTO.PageSize)
            .ToListAsync();

        var totalCount = await query.CountAsync();

        return RequestResponse.OK(new PageResult<BlogTextView>(list, totalCount), "查询成功");
    }

    #endregion

    #region 新增博客文章

    /// <summary>
    ///     新增博客文章
    /// </summary>
    public async Task<RequestResponseModel> AddBlogText(BlogTextAddDTO addDTO)
    {
        //校验博客用户
        var blogUser = await Valid.ValidId(_context.BlogUser, _userContext.UserId);
        if (blogUser == null) return RequestResponse.BadRequest("用户不存在");
        
        var entity = _mapper.Map<BlogTextModel>(addDTO);
        entity.Id = Guid.NewGuid();
        entity.UserId = blogUser.Id;
        entity.UserCode = blogUser.Code;
        entity.UserName = blogUser.Name;
        entity.CreateTime = DateTime.Now;

        _context.BlogText.Add(entity);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(entity.Id, "新增成功");
    }

    #endregion

    #region 更新博客文章

    /// <summary>
    ///     更新博客文章
    /// </summary>
    public async Task<RequestResponseModel> PutBlogText(BlogTextUpdateDTO updateDTO)
    {
        var existing = await Valid.ValidId(_context.BlogText, updateDTO.Id);
        if (existing == null)
            return RequestResponse.ErrorRequest("博客文章ID无效");

        _mapper.Map(updateDTO, existing);
        _context.BlogText.Update(existing);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(updateDTO.Id, "更新成功");
    }

    #endregion

    #region 删除博客文章

    /// <summary>
    ///     删除博客文章
    /// </summary>
    public async Task<RequestResponseModel> DeleteBlogText(SingleIdDTO deleteDTO)
    {
        var entity = await Valid.ValidId(_context.BlogText, deleteDTO.Id);
        if (entity == null)
            return RequestResponse.ErrorRequest("博客文章ID无效");

        _context.BlogText.Remove(entity);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(deleteDTO.Id, "删除成功");
    }

    #endregion

    #region 审核通过博客文章

    public async Task<RequestResponseModel> PassBlogText(IdArrayDTO idArrayDTO)
    {
        if (idArrayDTO == null || idArrayDTO.Ids == null || idArrayDTO.Ids.Count == 0)
            return RequestResponse.ErrorRequest("博客文章IDs列表无效");
        //查询列表
        var textList = await _context.BlogText
            .Where(a => idArrayDTO.Ids.Contains(a.Id.ToString()))
            .Where(a => a.Status == BlogEnum.ExamStatusEnum.待审核)
            .ToListAsync();
        //判定查询结果和传入id数量是否一致
        if (textList.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("博客文章IDs列表中有ID是无效的或者不是待审核状态");
        //数量结果一致，开始调整状态
        foreach (var text in textList) text.Status = BlogEnum.ExamStatusEnum.审核通过;
        //保存数据库并返回成功
        _context.BlogText.UpdateRange(textList);
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO, "审核通过成功");
    }

    #endregion

    #region 审核不通过博客文章

    public async Task<RequestResponseModel> UnPassBlogText(IdArrayDTO idArrayDTO)
    {
        if (idArrayDTO == null || idArrayDTO.Ids == null || idArrayDTO.Ids.Count == 0)
            return RequestResponse.ErrorRequest("博客文章IDs列表无效");
        //查询列表
        var textList = await _context.BlogText
            .Where(a => idArrayDTO.Ids.Contains(a.Id.ToString()))
            .Where(a => a.Status == BlogEnum.ExamStatusEnum.待审核)
            .ToListAsync();
        //判定查询结果和传入id数量是否一致
        if (textList.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("博客文章IDs列表中有ID是无效的或者不是待审核状态");
        //数量结果一致，开始调整状态
        foreach (var text in textList) text.Status = BlogEnum.ExamStatusEnum.审核不通过;
        //保存数据库并返回成功
        _context.BlogText.UpdateRange(textList);
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO, "审核不通过成功");
    }

    #endregion
}